//关联服务
define(function(require) {
	'use strict';

	//开启自定义指令
	var directives = angular.module('starter.directives', []);

	//评价星星选择控件
	directives.directive('star', function() {
		return {
			template: '<ul class="rating" ng-mouseleave="leave()">' +
				'<li ng-repeat="star in stars" ng-class="star" ng-click="click($index + 1)" ng-mouseover="over($index + 1)">' +
				'\u2605' +
				'</li>' +
				'</ul>',
			scope: {
				ratingValue: '=',
				max: '=',
				readonly: '@',
				onHover: '=',
				onLeave: '='
			},
			controller: function($scope) {
				$scope.ratingValue = $scope.ratingValue || 0;
				$scope.max = $scope.max || 5;
				$scope.click = function(val) {
					if($scope.readonly && $scope.readonly === 'true') {
						return;
					}
					$scope.ratingValue = val;
				};
				$scope.over = function(val) {
					$scope.onHover(val);
				};
				$scope.leave = function() {
					$scope.onLeave();
				}
			},
			link: function(scope, elem, attrs) {
				elem.css("text-align", "center");
				var updateStars = function() {
					scope.stars = [];
					for(var i = 0; i < scope.max; i++) {
						scope.stars.push({
							filled: i < scope.ratingValue
						});
					}
				};
				updateStars();

				scope.$watch('ratingValue', function(oldVal, newVal) {
					if(newVal) {
						updateStars();
					}
				});
				scope.$watch('max', function(oldVal, newVal) {
					if(newVal) {
						updateStars();
					}
				});
			}
		};
	});

	directives.directive('embedSrc', function() {
		return {
			restrict: 'A',
			link: function(scope, element, attrs) {
				var current = element;
				scope.$watch(attrs.embedSrc, function() {
					//          	console.log(current);
					var clone = element.clone().attr('src', attrs.embedSrc);
					current.replaceWith(clone);
					current = clone;
				});
			}
		};
	});

	directives.directive('abc', function() {
		return {
			restrict: 'A',
			scope: false,
			link: function(scope, element, attrs) {

				var elWidth, elHeight;

				// mode : 'pinch' or 'swipe'
				var mode = '';

				// distance between two touche points (mode : 'pinch')
				var distance = 0;
				var initialDistance = 0;

				// image scaling
				var scale = 1;
				var relativeScale = 1;
				var initialScale = 1;
				var maxScale = parseInt(attrs.maxScale, 10);
				if(isNaN(maxScale) || maxScale <= 1) {
					maxScale = 3;
				}

				// position of the upper left corner of the element
				var positionX = 0;
				var positionY = 0;

				var initialPositionX = 0;
				var initialPositionY = 0;

				// central origin (mode : 'pinch')
				var originX = 0;
				var originY = 0;

				// start coordinate and amount of movement (mode : 'swipe')
				var startX = 0;
				var startY = 0;
				var moveX = 0;
				var moveY = 0;

				var image = new Image();
				image.onload = function() {
					elWidth = element[0].clientWidth;
					elHeight = element[0].clientHeight;

					element.css({
						'-webkit-transform-origin': '0 0',
						'transform-origin': '0 0'
					});

					element.on('touchstart', touchstartHandler);
					element.on('touchmove', touchmoveHandler);
					element.on('touchend', touchendHandler);
				};

				if(attrs.ngSrc) {
					image.src = attrs.ngSrc;
				} else {
					image.src = attrs.src;
				}

				/**
				 * @param {object} evt
				 */
				function touchstartHandler(evt) {
					var touches = evt.originalEvent ? evt.originalEvent.touches : evt.touches;

					startX = touches[0].clientX;
					startY = touches[0].clientY;
					initialPositionX = positionX;
					initialPositionY = positionY;
					moveX = 0;
					moveY = 0;
				}

				/**
				 * @param {object} evt
				 */
				function touchmoveHandler(evt) {
					var touches = evt.originalEvent ? evt.originalEvent.touches : evt.touches;

					if(mode === '') {
						if(touches.length === 1 && scale > 1) {

							mode = 'swipe';

						} else if(touches.length === 2) {

							mode = 'pinch';

							initialScale = scale;
							initialDistance = getDistance(touches);
							originX = touches[0].clientX -
								parseInt((touches[0].clientX - touches[1].clientX) / 2, 10) -
								element[0].offsetLeft - initialPositionX;
							originY = touches[0].clientY -
								parseInt((touches[0].clientY - touches[1].clientY) / 2, 10) -
								element[0].offsetTop - initialPositionY;

						}
					}

					if(mode === 'swipe') {
						evt.preventDefault();

						moveX = touches[0].clientX - startX;
						moveY = touches[0].clientY - startY;

						positionX = initialPositionX + moveX;
						positionY = initialPositionY + moveY;

						transformElement();

					} else if(mode === 'pinch') {
						evt.preventDefault();

						distance = getDistance(touches);
						relativeScale = distance / initialDistance;
						scale = relativeScale * initialScale;

						positionX = originX * (1 - relativeScale) + initialPositionX + moveX;
						positionY = originY * (1 - relativeScale) + initialPositionY + moveY;

						transformElement();

					}
				}

				/**
				 * @param {object} evt
				 */
				function touchendHandler(evt) {
					var touches = evt.originalEvent ? evt.originalEvent.touches : evt.touches;

					if(mode === '' || touches.length > 0) {
						return;
					}

					if(scale < 1) {

						scale = 1;
						positionX = 0;
						positionY = 0;

					} else if(scale > maxScale) {

						scale = maxScale;
						relativeScale = scale / initialScale;
						positionX = originX * (1 - relativeScale) + initialPositionX + moveX;
						positionY = originY * (1 - relativeScale) + initialPositionY + moveY;

					} else {

						if(positionX > 0) {
							positionX = 0;
						} else if(positionX < elWidth * (1 - scale)) {
							positionX = elWidth * (1 - scale);
						}
						if(positionY > 0) {
							positionY = 0;
						} else if(positionY < elHeight * (1 - scale)) {
							positionY = elHeight * (1 - scale);
						}

					}

					transformElement(0.1);
					mode = '';
				}

				/**
				 * @param {Array} touches
				 * @return {number}
				 */
				function getDistance(touches) {
					var d = Math.sqrt(Math.pow(touches[0].clientX - touches[1].clientX, 2) +
						Math.pow(touches[0].clientY - touches[1].clientY, 2));
					return parseInt(d, 10);
				}

				/**
				 * @param {number} [duration]
				 */
				function transformElement(duration) {
					var transition = duration ? 'all cubic-bezier(0,0,.5,1) ' + duration + 's' : '';
					var matrixArray = [scale, 0, 0, scale, positionX, positionY];
					var matrix = 'matrix(' + matrixArray.join(',') + ')';

					element.css({
						'-webkit-transition': transition,
						transition: transition,
						'-webkit-transform': matrix + ' translate3d(0,0,0)',
						transform: matrix
					});
				}
			}
		};
	});

	//自定义指令
	directives.directive("rightsCtrl", function(Auth, GoDialog, $rootScope) {
		return {
			restrict: "A", // 指令类型  E：element A：attribute M：comment C: class
			link: function(scope, element, attrs, controller) {
				//回调产生
				Auth.get_check_user_auth(attrs.authname, function(isHave) {
					var type = attrs.type;
					//使用方法分2种：
					//（1）tab页面，则标题加入data-authname="销售中商品" rights-ctrl，相应的slide主体加入data-authname="销售中商品" data-type="slide" rights-ctrl
					//（2）不是tab页面，则data-authname="发票管理" rights-ctrl即可
					//设置样式    方式1：（1）去掉绑定事件 attrs.ngClick = ""；（2）字体颜色变灰'color': '#999'    方式2：直接隐藏
					if(!isHave) { //如果没有权限
						if(type == "slide") { //如果是tab的内容体，不能'display':'none'，否则切换时可能切换到别的tab页
							element.css({
								'visibility': 'hidden'
							});
						} else {
							element.css({
								'display': 'none'
							});
						}
					}

					//绑定事件  data-tabnumber="0" data-authname="销售中商品"(权限名称)  rights-ctrl
					//				element.bind("click", function(e) {
					//					//商品编辑权限
					//					var tabnumber = this.dataset.tabnumber;//tab页面的序号
					//					if(isHave) {//有权限
					//						if(tabnumber) {//如果是tab页面
					//							scope.activeSlide(tabnumber);
					//						}
					//					}else {
					////						attrs.ngClick = "";//在这里没效果
					//						GoDialog.toast("对不起, 您没有权限！");
					//					}
					//					
					//				})
				});
			}
		};
	});

	//我的未来万家  权限控制
	directives.directive("rightsCtrlMenu", function(Auth, GoDialog, $rootScope) {
		return {
			restrict: "A",
			link: function(scope, element, attrs, controller) {
				//回调产生
				Auth.get_check_user_auth_menu(attrs.authname, function(isHave) {
					//					console.log(attrs.authname)
					//					console.log(isHave)
					if(!isHave) { //如果没有权限
						element.css({
							'display': 'none'
						});
					}
				});
			}
		};
	});

	return directives;
});